package com.zzk.lanouhn.myapplication1.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.jude.rollviewpager.RollPagerView;
import com.zzk.lanouhn.myapplication1.R;
import com.zzk.lanouhn.myapplication1.activity.AllNewsDetailsActivity;
import com.zzk.lanouhn.myapplication1.adapters.RollViewPagerAdapter;
import com.zzk.lanouhn.myapplication1.adapters.ScrollRecyclerViewAdapter;
import com.zzk.lanouhn.myapplication1.intefaces.NewsItemCliclListener;
import com.zzk.lanouhn.myapplication1.modles.Adpic;
import com.zzk.lanouhn.myapplication1.modles.AllNews;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 新闻->全部页面
 * Created by lanouhn on 16/8/23.
 */
public class NewsAllFragment extends Fragment implements NewsItemCliclListener {


    private XRecyclerView scrollRecyclerView;
    private ScrollRecyclerViewAdapter srva;
    private Adpic adpic;    //轮播图实体类
    private List<AllNews.Datas.DataBean> allNews=new ArrayList<>();//新闻内容实体类
    private List<AllNews.Datas.DataBean> tempNews=new ArrayList<>();//缓存数据
    private RollPagerView rollPagerView;
    private RollViewPagerAdapter adapter;
    private int page = 20;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_news_all, null);
        scrollRecyclerView = (XRecyclerView) view.findViewById(R.id.scroll_news);

        //rollPagerView = (RollPagerView) view.findViewById(R.id.roll_view_pager_news);
        scrollRecyclerView.setFocusable(false);
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        scrollRecyclerView.setLayoutManager(manager);
        //上拉加载的动画效果
        scrollRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        //下拉刷新的动画效果
        scrollRecyclerView.setArrowImageView(R.drawable.ic_loading_rotate);
        scrollRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            //下拉刷新
            @Override
            public void onRefresh() {
                page = 20;
                getDataFromWeb();
            }

            //上拉加载
            @Override
            public void onLoadMore() {
                page+=20;
                getDataFromWeb();
            }
        });
        rollPagerView=new RollPagerView(getActivity());
        rollPagerView.setPlayDelay(5000);
        rollPagerView.setAnimationDurtion(2000);
        LinearLayout.LayoutParams imagebtn_params = new LinearLayout.LayoutParams(

                LinearLayout.LayoutParams.WRAP_CONTENT, 250);
        rollPagerView.setLayoutParams(imagebtn_params);
        scrollRecyclerView.addHeaderView(rollPagerView);
        getDataFromWeb();

        return view;

    }
    private void getDataFromWeb() {
        /**
         * 获取新闻
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                String s=String.valueOf(page);
                String url = "https://rong.36kr.com/api/mobi/news?pageSize="+s+"&columnId=all&pagingAction=up";
                OkHttpClient client1 = new OkHttpClient();
                Request request1 = new Request.Builder()
                        .url(url)
                        .build();
                Call call1 = client1.newCall(request1);
                call1.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        // Toast.makeText(getActivity(), "网络请求失败", Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result1 = response.body().string();
                        Gson gson1 = new Gson();
                        tempNews = gson1.fromJson(result1, AllNews.class).getDatas().getData();
                        if (tempNews.size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(0);
                        }
                        /**
                         * 获取轮播图
                         */
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                String imageUrl = "https://rong.36kr.com/api/mobi/roundpics/v4";
                                OkHttpClient client2 = new OkHttpClient();
                                Request request2 = new Request.Builder()
                                        .url(imageUrl)
                                        .build();

                                Call call2 = client2.newCall(request2);
                                call2.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {


                                        // Toast.makeText(getActivity(), "网络请求失败", Toast.LENGTH_SHORT).show();

                                    }

                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String result2 = response.body().string();
                                        Gson gson2 = new Gson();
                                        adpic = gson2.fromJson(result2, Adpic.class);
                                        if (adpic.getData().getPics().size() > 0) {
                                            handler.sendEmptyMessage(2);
                                        } else {
                                            handler.sendEmptyMessage(0);
                                        }
                                    }
                                });
                            }
                        }).start();
                    }
                });

            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Toast.makeText(getActivity(), "请求数据失败", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    if (page == 20) {
                        allNews.clear();
                        allNews.addAll(tempNews);
                        srva = new ScrollRecyclerViewAdapter(getActivity(), allNews);
                        srva.setScrollRecyclerViewAdapter(NewsAllFragment.this);
                        scrollRecyclerView.setAdapter(srva);
                        scrollRecyclerView.refreshComplete();
                        tempNews.clear();
                    } else {
                        allNews.addAll(tempNews);
                        srva.notifyDataSetChanged();
                        scrollRecyclerView.loadMoreComplete();
                        tempNews.clear();
                    }
                    break;
                case 2:
                    adapter = new RollViewPagerAdapter(getActivity(), adpic);
                    rollPagerView.setAdapter(adapter);
                    break;
                default:

                    break;
            }
        }
    };

    @Override
    public void onItemClick(int position) {
        Intent intent = new Intent(getActivity(), AllNewsDetailsActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("详情", allNews.get(position-2).getFeedId().toString());
        intent.putExtras(bundle);
        startActivity(intent);

    }
}
